package com.sinosoft.cnmuseum.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import com.sinosoft.cnmuseum.dao.MbGyFileDao;
import com.sinosoft.cnmuseum.entity.MbGyFile;
import com.sinosoft.commontools.record.Record;

public class MultipartFile {
	
	public Record RecvFile(HttpServletRequest request) {
		Record r = new Record();
		r.add("status", "ok");
		FileItemFactory factory=new DiskFileItemFactory();		//针对磁盘文件创建工厂
		ServletFileUpload upload=new ServletFileUpload(factory);//通过factory创建一个ServletFileUpload
		upload.setHeaderEncoding("UTF-8");//设成你的编码格式
		try {
			List<FileItem> items=upload.parseRequest(request);  //解析请求，获得表单上的一些选项。
			Iterator<FileItem> iter=items.iterator();
			while(iter.hasNext()){
				FileItem item=(FileItem)iter.next();  //取出封装成文件选项
				if(!item.isFormField()){		//判断一个参数域是普通的表单输入域,还是文件上传域
					String filenameold = item.getName(); //得到要上传的文件的绝对路径
					String filename = FileUtils.getDateFileByFileName(filenameold);
					String savePath = FileUtils.getUpladFilePathByRelativePath(filename);
					File f = new File(savePath);

					if(f.exists()){
						f.delete();
					}
					item.write(new File(savePath));
					r.add("filename",filenameold);
					r.add("savePath", savePath);
				}	
			}
		} catch (Exception e) {
			e.printStackTrace();
			r.add("status", "failed");
		}
		return r;
	} 

	
	
	/**
	 * 获取文件id
	 * @param request
	 * @return
	 */
	public String getFileid(HttpServletRequest request) {
		Record result = new Record();
		try{
			Record file = RecvFile(request);
			if(file == null) {
				throw new Exception("插入信息失败！");
			}
			MbGyFileDao dao = new MbGyFileDao();
			String filename = file.getStrValue("filename");
			String savePath = file.getStrValue("savePath");
			Record gyfile = new Record();
			String uuid24 = StringUtils.getUUID24();
			gyfile.add("id", uuid24);
			gyfile.add("filename", filename);
			gyfile.add("savePath", savePath);			
			if(dao.insert(gyfile)){			
				// 事务模式下，此标识将使此次事务提交
				String id = gyfile.getStrValue(MbGyFile.ID);
				result.add(MbGyFile.ID, id);
				result.add(Status.SATUS,Status.OK);
			}else{
				throw new Exception("插入信息失败！");
			}
		} catch (Exception e) {			
			e.printStackTrace();			
			result.add(Status.SATUS, Status.FAILED);
		}
		String fileid = result.getStrValue("id");
	    return fileid;
	}
	
	public  Record getFileData(HttpServletRequest request) {
		Record result = new Record();
		try{     
			MultipartFile multipartFile =new MultipartFile();
			Record file = multipartFile.RecvFile(request);
			MbGyFileDao dao = new MbGyFileDao();
			String filename = file.getStrValue("filename");
			String savePath = file.getStrValue("savePath");
			
			ImageUtils img = new ImageUtils(savePath);
			long s_b = img.getSize();
			float s_kb = s_b/1024;
			int height = img.getHeight();
			int width = img.getWidth();
			
			Record gyfile = new Record();
			String uuid24 = StringUtils.getUUID24();
			gyfile.add("id", uuid24);
			gyfile.add("filename", filename);
			gyfile.add("savePath", savePath);			
			if(dao.insert(gyfile)){			
				// 事务模式下，此标识将使此次事务提交
				String id = gyfile.getStrValue(MbGyFile.ID);
				result.add(MbGyFile.ID, id);
				result.add("s_b", s_b);
				result.add("s_kb", s_kb);
				result.add("height", height);
				result.add("width", width);
				result.add(Status.SATUS,Status.OK);
			}else{
				throw new Exception("插入信息失败！");
			}
		} catch (Exception e) {			
			e.printStackTrace();			
			result.add(Status.SATUS, Status.FAILED);
		}
	    return result;
	}
	
	
	/**
	 * 删除文件记录和本地文件
	 * @param id
	 * @return
	 */
	public  void deleteFileData(String id) {			
		Record result = new Record();
		try{     		
			MbGyFileDao dao = new MbGyFileDao();	
			String sql = "select * from "+MbGyFile.MB_GY_FILE_TABLE_NAME+" where 1=1 and "+MbGyFile.ID+"='"+id+"' ";
			List<Record> list = dao.getBySql(sql);	
			Record file = list.get(0);
			String savePath = file.getStrValue("savePath");		
			File oldfile=new File(savePath);
			if(oldfile.isFile()){
				oldfile.delete();
			}
						
			if(dao.delete(file)){			
				// 事务模式下，此标识将使此次事务提交
				result.add(Status.SATUS,Status.OK);
			}else{
				throw new Exception("删除信息失败！");
			}
		} catch (Exception e) {			
			e.printStackTrace();			
			result.add(Status.SATUS, Status.FAILED);
		}

	}
	

	/**
	 * 获取文件大小和高度和宽度
	 * @param id
	 * @return
	 */
	public  Record getFileDetailData(String id) {	
		Record result = new Record();
		try{     
			MbGyFileDao dao = new MbGyFileDao();	
			String sql = "select * from "+MbGyFile.MB_GY_FILE_TABLE_NAME+" where 1=1 and "+MbGyFile.ID+"='"+id+"' ";
			List<Record> list = dao.getBySql(sql);	
			Record file = list.get(0);
			String savePath = file.getStrValue("savePath");	
			String filename = file.getStrValue("filename");
			
			ImageUtils img = new ImageUtils(savePath);
			long s_b = img.getSize();
			float s_kb = s_b/1024;
			int height = img.getHeight();
			int width = img.getWidth();
			
			result.add("s_b", s_b);
			result.add("s_kb", s_kb);
			result.add("height", height);
			result.add("width", width);
			result.add("filename", filename);
			result.add(Status.SATUS,Status.OK);
		} catch (Exception e) {			
			e.printStackTrace();			
			result.add(Status.SATUS, Status.FAILED);
		}
	    return result;
	}
	
	/**
	 * 下载文件
	 * @param request
	 * @param response
	 * @param id
	 */
	public void downFile(HttpServletRequest request, HttpServletResponse response, String id){
		try {
			MbGyFileDao dao = new MbGyFileDao();		
			String sql = "select * from "+MbGyFile.MB_GY_FILE_TABLE_NAME+" where 1=1 and "+MbGyFile.ID+"='"+id+"' ";
			List<Record> list = dao.getBySql(sql);	
			Record file = list.get(0);
			String filename = file.getStrValue("filename");
			String savePath = file.getStrValue("savePath");
			File newfile = new File(savePath);
			response.setCharacterEncoding("UTF-8");
			response.setContentLength((int) newfile.length()); 
			// 设置中文编码 防止乱码
			filename = new String(filename.getBytes(), "ISO-8859-1"); 
			// 设置在下载框默认显示的文件名  
            response.setHeader("Content-Disposition", "attachment;filename="+ filename);
            response.setContentType("application/octet-stream");// 指明response的返回对象是文件流  
            //读取文件  
            InputStream in = new FileInputStream(savePath);  
            OutputStream out = response.getOutputStream();  
            //写文件  
            byte[] buff = new byte[2048];
            int bytesRead;
            while (-1 != (bytesRead = in.read(buff, 0, buff.length))) {
            	out.write(buff, 0, bytesRead);
            }
            in.close();  
            out.close(); 
		} catch (Exception e) {
			try {
				response.setHeader("Content-type", "text/html;charset=UTF-8"); 
				response.setContentType("text/plain");
				response.setCharacterEncoding("UTF-8");
				String jsstr = "文件不存在";
				response.getOutputStream().write(jsstr.getBytes("UTF-8"));
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
	}
	
	
	
}